Make Event's location accessible from Liquid templates.

Akinori MUSHA 10 years ago
parent
commit
dd507e3cbf
4 changed files with 37 additions and 0 deletions
  1. 4 0
      app/models/event.rb
  2. 14 0
      lib/location.rb
  3. 12 0
      spec/lib/location_spec.rb
  4. 7 0
      spec/models/event_spec.rb

+ 4 - 0
app/models/event.rb

@@ -117,4 +117,8 @@ class EventDrop
117 117
       @object.created_at
118 118
     }
119 119
   end
120
+
121
+  def _location_
122
+    @object.location
123
+  end
120 124
 end

+ 14 - 0
lib/location.rb

@@ -1,6 +1,10 @@
1
+require 'liquid'
2
+
1 3
 Location = Struct.new(:lat, :lng, :radius, :speed, :course)
2 4
 
3 5
 class Location
6
+  include LiquidDroppable
7
+
4 8
   protected :[]=
5 9
 
6 10
   def initialize(data = {})
@@ -86,3 +90,13 @@ class Location
86 90
     end
87 91
   end
88 92
 end
93
+
94
+class LocationDrop
95
+  KEYS = Location.members.map(&:to_s).concat(%w[latitude longitude])
96
+
97
+  def before_method(key)
98
+    if KEYS.include?(key)
99
+      @object.__send__(key)
100
+    end
101
+  end
102
+end

+ 12 - 0
spec/lib/location_spec.rb

@@ -53,4 +53,16 @@ describe Location do
53 53
     expect(Location.new(lat: 2, radius: 1).present?).to be_falsy
54 54
     expect(Location.new(lng: 3, radius: 1).present?).to be_falsy
55 55
   end
56
+
57
+  it "is droppable" do
58
+    {
59
+      '{{location.lat}}' => '2.0',
60
+      '{{location.latitude}}' => '2.0',
61
+      '{{location.lng}}' => '3.0',
62
+      '{{location.longitude}}' => '3.0',
63
+    }.each { |template, result|
64
+      expect(Liquid::Template.parse(template).render('location' => location.to_liquid)).to eq(result),
65
+        "expected #{template.inspect} to expand to #{result.inspect}"
66
+    }
67
+  end
56 68
 end

+ 7 - 0
spec/models/event_spec.rb

@@ -174,6 +174,8 @@ describe EventDrop do
174 174
       'title' => 'some title',
175 175
       'url' => 'http://some.site.example.org/',
176 176
     }
177
+    @event.lat = 2
178
+    @event.lng = 3
177 179
     @event.save!
178 180
   end
179 181
 
@@ -210,4 +212,9 @@ describe EventDrop do
210 212
     t = '{{created_at | date:"%FT%T%z" }}'
211 213
     interpolate(t, @event).should eq(@event.created_at.strftime("%FT%T%z"))
212 214
   end
215
+
216
+  it 'should have _location_' do
217
+    t = '{{_location_.lat}},{{_location_.lng}}'
218
+    interpolate(t, @event).should eq("2.0,3.0")
219
+  end
213 220
 end